package com.example.springbootdemo2024.controller;

import com.example.springbootdemo2024.dao.UserDao;
import com.example.springbootdemo2024.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserDao userDao;//依赖注入

    /**
     * 跳转到登录页面
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    /**
     * 跳转到用户信息管理
     */
    @RequestMapping("/toUserInfo")
    public String toUserInfo(){
        return "userInfo";
    }

    /**
     * 用户登录
     */
    @RequestMapping("/login")
    @ResponseBody
    public String login(User user, HttpServletRequest request){
        List<User> users = userDao.login(user);
        if(users.size() == 1){//登录成功
            //用户信息存储到session中
            HttpSession session = request.getSession();//生成session对象
            String phone = users.get(0).getPhone();
            Integer userid = users.get(0).getId();
            session.setAttribute("phone", phone);//将手机号存入session
            session.setAttribute("userid", userid);//将用户id存入session
            //获取session内容为：session.getAttribute("phone")
            if("admin".equals(phone)){//管理员登录
                return "admin";
            }
            else{//普通用户登录
                return "user";
            }
        }
        else{//登录失败
            return "false";
        }
    }

    /**
     * 获取phone
     */
    @RequestMapping("/getPhone")
    @ResponseBody
    public String getPhone(HttpServletRequest request){
        HttpSession session = request.getSession();//生成session对象
        String phone = (String)session.getAttribute("phone");
        return phone;
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    @ResponseBody
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession();//生成session对象
        session.removeAttribute("phone");
        session.removeAttribute("userid");
        return "成功退出";
    }
}
